<template>
  <div class="parent-school-system">
    <header class="header">
      <h1 class="title">家校联动</h1>
      <div class="search-container">
        <input type="text" class="search-input" placeholder="搜索..." v-model="searchQuery" />
        <button class="search-btn">查询</button>
      </div>
    </header>

    <main class="main-content">
      <!-- 主数据表格 -->
      <div class="data-table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>序号</th>
              <th>姓名</th>
              <th>测试名称</th>
              <th>状态</th>
              <th>成绩</th>
              <th>测试时间</th>
              <th>类型</th>
              <th>家长</th>
              <th>家长联系电话</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in pagedTestData" :key="item.id">
              <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
              <td>{{ item.studentName }}</td>
              <td>{{ item.testName }}</td>
              <td>{{ item.status }}</td>
              <td>{{ item.score }}</td>
              <td>{{ item.testDate }}</td>
              <td>{{ item.testType }}</td>
              <td>{{ item.parent.name }}</td>
              <td>{{ item.parent.phone }}</td>
              <td>
                <button class="send-btn" @click="openMessageDialog(item)">发送</button>
                <button class="manage-btn" @click="openManageDialog(item)">管理</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <button class="page-btn" @click="prevPage" :disabled="currentPage === 1">&lt;</button>
        <button class="page-btn" v-for="page in totalPagesComputed" :key="page" @click="currentPage = page"
          :class="{ active: currentPage === page }">
          {{ page }}
        </button>
        <button class="page-btn" @click="nextPage" :disabled="currentPage === totalPagesComputed">&gt;</button>
        <span class="page-jump">跳至</span>
        <input type="number" class="page-input" v-model.number="pageJump" min="1" :max="totalPagesComputed" />
        <span>页</span>
        <button class="confirm-btn" @click="jumpToPage">确定</button>
      </div>

      <!-- 消息对话框 -->
      <div class="message-dialog" v-if="showMessageDialog">
        <div class="dialog-content">
          <div class="dialog-header">
            <div class="dialog-title">
              <span>QQ邮箱</span>
              <span class="recipient">收件人: {{ selectedStudent?.parent.name }}</span>
            </div>
            <button class="close-btn" @click="closeMessageDialog">×</button>
          </div>

          <div class="dialog-body">
            <div class="form-group">
              <label>学生姓名:</label>
              <span>{{ selectedStudent?.studentName }}</span>
            </div>
            <div class="form-group">
              <label>考试时间:</label>
              <span>{{ selectedStudent?.testDate }}</span>
            </div>
            <div class="form-group">
              <label>考试科目:</label>
              <span>{{ selectedStudent?.testName }}</span>
            </div>
            <div class="form-group">
              <label>考试成绩:</label>
              <span>{{ selectedStudent?.score }}</span>
            </div>
            <div class="form-group">
              <label>教师寄语</label>
              <textarea v-model="teacherMessage" placeholder="请输入寄语内容..."></textarea>
            </div>
          </div>

          <div class="dialog-footer">
            <button class="cancel-btn" @click="closeMessageDialog">取消</button>
            <button class="confirm-send-btn" @click="sendMessage">发送</button>
          </div>
        </div>
      </div>

      <!-- 家长信息管理对话框 -->
      <div class="manage-dialog" v-if="showManageDialog">
        <div class="dialog-content">
          <div class="dialog-header">
            <div class="dialog-title">
              <span>管理家长信息</span>
            </div>
            <button class="close-btn" @click="closeManageDialog">×</button>
          </div>

          <div class="dialog-body">
            <div class="form-group">
              <label>家长姓名:</label>
              <input type="text" v-model="parentForm.name" placeholder="请输入家长姓名" />
            </div>
            <div class="form-group">
              <label>家长联系电话:</label>
              <input type="text" v-model="parentForm.phone" placeholder="请输入家长联系电话" />
            </div>
            <!-- 新增字段 -->
            <div class="form-group">
              <label>家长性别:</label>
              <input type="text" v-model="parentForm.gender" placeholder="请输入家长性别" />
            </div>
            <div class="form-group">
              <label>家长出生日期:</label>
              <input type="date" v-model="parentForm.birthDate" placeholder="请输入家长出生日期" />
            </div>
            <div class="form-group">
              <label>家长邮箱:</label>
              <input type="email" v-model="parentForm.email" placeholder="请输入家长邮箱" />
            </div>
            <div class="form-group">
              <label>家长地址:</label>
              <input type="text" v-model="parentForm.address" placeholder="请输入家长地址" />
            </div>
            <div class="form-group">
              <label>与学生关系:</label>
              <input type="text" v-model="parentForm.relationship" placeholder="请输入与学生关系" />
            </div>
          </div>

          <div class="dialog-footer">
            <button class="cancel-btn" @click="closeManageDialog">取消</button>
            <button class="confirm-send-btn" @click="saveParentInfo">保存</button>
          </div>
        </div>
      </div>

      <!-- 成功通知 -->
      <div class="notification" v-if="showNotification">
        <div class="notification-content">
          <p>{{ notificationMessage }}</p>
        </div>
      </div>
    </main>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue';
import { teacherApi } from '@/api/teacherApi';


interface ParentData {
  id: number;
  name: string;
  gender: string;
  birthDate: string;
  phone: string;
  email: string;
  address: string;
  relationship: string;
}

// 定义类型
interface TestData {
  id: number;
  studentName: string;
  testName: string;
  status: '完成' | '进行中' | '未开始';
  score: number | string;
  testDate: string;
  testType: '期中' | '期末' | '月考';
  parent: ParentData;
}

interface EmailRequest {
  parentEmail: string;
  studentName: string;
  testName: string;
  score: string | number;
  testDate: string;
  teacherMessage: string;
}


interface StudentStatistics {
  totalTests: number;
  completedTests: number;
  averageScore: number;
  totalScore: number;
}

interface StudentStatisticsMap {
  [key: string]: StudentStatistics;
}

interface Message {
  recipient: string;
  student: string;
  message: string;
  sentTime: string;
  test: string;
}

export default defineComponent({
  name: 'ParentSchoolSystem',
  setup() {
    const searchQuery = ref('');
    const currentPage = ref(1);
    const pageSize = ref(8); // 每页展示8条数据
    const pageJump = ref(1);
    const testData = ref<TestData[]>([]);
    const parentData = ref<ParentData[]>([]); // 家长数据

    const showMessageDialog = ref(false);
    const showManageDialog = ref(false);
    const selectedStudent = ref<TestData | null>(null);
    const selectedParent = ref<ParentData | null>(null);
    const parentForm = ref({
      id: 0,
      name: '',
      gender: '',
      birthDate: '',
      phone: '',
      email: '',
      address: '',
      relationship: ''
    });
    const teacherMessage = ref('');
    const showNotification = ref(false);
    const notificationMessage = ref('');
    const studentStatistics = ref<StudentStatisticsMap>({});
    const recentMessages = ref<Message[]>([]);

    // 过滤数据的计算属性
    const filteredTestData = computed(() => {
      if (!searchQuery.value) {
        return testData.value;
      }

      return testData.value.filter(item => {
        return item.studentName.includes(searchQuery.value) ||
          item.testName.includes(searchQuery.value) ||
          item.parent.name.includes(searchQuery.value);
      });
    });

    // 当前页数据的计算属性
    const pagedTestData = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      return filteredTestData.value.slice(startIndex, endIndex);
    });

    // 总页数的计算属性
    const totalPagesComputed = computed(() => {
      return Math.ceil(filteredTestData.value.length / pageSize.value);
    });

    // 上一页
    const prevPage = (): void => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };

    // 下一页
    const nextPage = (): void => {
      if (currentPage.value < totalPagesComputed.value) {
        currentPage.value++;
      }
    };

    // 跳转到指定页
    const jumpToPage = (): void => {
      const page = parseInt(pageJump.value.toString());
      if (page >= 1 && page <= totalPagesComputed.value) {
        currentPage.value = page;
      }
    };

    // 对话框相关方法
    const openMessageDialog = (student: TestData): void => {
      selectedStudent.value = student;
      showMessageDialog.value = true;

      if (student.status === '完成') {
        const score = typeof student.score === 'string' ? 0 : student.score;
        if (score >= 90) {
          teacherMessage.value = `${student.studentName}同学在${student.testName}中表现优异，取得了${student.score}分的好成绩。希望继续保持良好的学习状态！`;
        } else if (score >= 80) {
          teacherMessage.value = `${student.studentName}同学在${student.testName}中表现良好，取得了${student.score}分。仍有进步空间，继续加油！`;
        } else {
          teacherMessage.value = `${student.studentName}同学在${student.testName}中取得了${student.score}分。需要加强复习，老师会提供额外辅导。`;
        }
      } else if (student.status === '进行中') {
        teacherMessage.value = `${student.studentName}同学正在参加${student.testName}，预计完成时间为${student.testDate}。`;
      } else {
        teacherMessage.value = `${student.studentName}同学将于${student.testDate}参加${student.testName}，请家长提醒学生做好考试准备。`;
      }
    };

    const openManageDialog = (student: TestData): void => {
      selectedStudent.value = student;
      showManageDialog.value = true;

      // 假设我们有一个方法可以根据学生 ID 获取对应的家长信息
      const parent = parentData.value.find(p => p.id === student.id);
      if (parent) {
        selectedParent.value = parent;
        parentForm.value = {
          id: parent.id,
          name: parent.name,
          gender: parent.gender,
          birthDate: parent.birthDate,
          phone: parent.phone,
          email: parent.email,
          address: parent.address,
          relationship: parent.relationship
        };
      } else {
        // 如果没有找到家长信息，初始化表单
        parentForm.value = {
          id: student.id,
          name: '',
          gender: '',
          birthDate: '',
          phone: '',
          email: '',
          address: '',
          relationship: ''
        };
      }
    };

    const closeMessageDialog = (): void => {
      showMessageDialog.value = false;
      selectedStudent.value = null;
      teacherMessage.value = '';
    };

    const closeManageDialog = (): void => {
      showManageDialog.value = false;
      selectedStudent.value = null;
      selectedParent.value = null;
    };

    // 发送消息相关方法
const sendMessage = async (): Promise<void> => {
  const student = selectedStudent.value;

  if (!student) {
    return;
  }

  // 构造请求体，明确类型为 EmailRequest
  const emailRequest: EmailRequest = {
    parentEmail: student.parent.email,
    studentName: student.studentName,
    testName: student.testName,
    score: student.score,
    testDate: student.testDate,
    teacherMessage: teacherMessage.value
  };

  try {
    // 调用封装后的发送邮件接口
    const response = await teacherApi.sendMessage(emailRequest);
    console.log('邮件发送响应:', response);

    if (response.msg === '邮件发送成功') {
      notificationMessage.value = `消息已成功发送至${student.parent.name}(${student.parent.phone})`;
      showNotification.value = true;

      setTimeout(() => {
        showNotification.value = false;
      }, 3000);

      closeMessageDialog();
    } else {
      notificationMessage.value = '邮件发送失败，请稍后再试';
      showNotification.value = true;

      setTimeout(() => {
        showNotification.value = false;
      }, 3000);
    }
  } catch (error) {
    console.error('邮件发送失败:', error);
    notificationMessage.value = '邮件发送失败，请稍后再试';
    showNotification.value = true;

    setTimeout(() => {
      showNotification.value = false;
    }, 3000);
  }
};

    // 保存家长信息相关方法
    const saveParentInfo = (): void => {
      const student = selectedStudent.value;

      if (!student) {
        return;
      }

      // 更新家长信息
      const updatedParentIndex = parentData.value.findIndex(item => item.id === parentForm.value.id);
      if (updatedParentIndex !== -1) {
        parentData.value[updatedParentIndex] = parentForm.value;
      } else {
        parentData.value.push(parentForm.value);
      }

      // 更新学生信息中的家长名称和电话
      const updatedStudentIndex = testData.value.findIndex(item => item.id === student.id);
      if (updatedStudentIndex !== -1) {
        testData.value[updatedStudentIndex].parent.name = parentForm.value.name;
        testData.value[updatedStudentIndex].parent.phone = parentForm.value.phone;
      }

      notificationMessage.value = `家长信息已更新`;
      showNotification.value = true;

      setTimeout(() => {
        showNotification.value = false;
      }, 3000);

      closeManageDialog();
    };

    // 使用 API 获取考试和家长信息
    const fetchExamAndParentInfo = async () => {
      try {
        const result = await teacherApi.getExamAndParentInfo();

        if (Array.isArray(result.data)) {
          // 映射后端返回的数据到前端定义的类型
          testData.value = result.data.map(item => {
            return {
              ...item,
              parent: {
                id: item.parent.parentid,
                name: item.parent.parentname, // 使用前端定义的 name 字段
                gender: item.parent.gender,
                birthDate: item.parent.birthdate,
                phone: item.parent.contactphone,
                email: item.parent.email,
                address: item.parent.address,
                relationship: item.parent.relationship
              }
            } as TestData;
          });

          // 提取家长信息并填充到 parentData
          parentData.value = testData.value.map(student => student.parent);

          console.log(testData.value);
          console.log(parentData.value);

        } else {
          console.error('获取的数据格式不符合期望的 TestData[] 类型');
          notificationMessage.value = '获取的数据格式不符合期望，请检查接口返回';
          showNotification.value = true;

          setTimeout(() => {
            showNotification.value = false;
          }, 3000);
        }
      } catch (error) {
        console.error('获取考试和家长信息失败:', error);
        notificationMessage.value = '获取考试和家长信息失败，请稍后再试';
        showNotification.value = true;

        setTimeout(() => {
          showNotification.value = false;
        }, 3000);
      }
    };
    // 在组件挂载时调用 API 获取数据
    onMounted(() => {
      fetchExamAndParentInfo();
    });

    return {
      searchQuery,
      currentPage,
      pageSize,
      pageJump,
      testData,
      parentData,
      showMessageDialog,
      showManageDialog,
      selectedStudent,
      selectedParent,
      parentForm,
      teacherMessage,
      showNotification,
      notificationMessage,
      studentStatistics,
      recentMessages,
      filteredTestData,
      pagedTestData,
      totalPagesComputed,
      prevPage,
      nextPage,
      jumpToPage,
      openMessageDialog,
      openManageDialog,
      closeMessageDialog,
      closeManageDialog,
      sendMessage,
      saveParentInfo
    };
  }
});
</script>

<style scoped>
.parent-school-system {
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 24px;
  color: #333;
}

.search-container {
  display: flex;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  width: 250px;
}

.search-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  padding: 8px 16px;
  cursor: pointer;
}

.data-table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.data-table tr:nth-child(even) {
  background-color: #fafafa;
}

.send-btn,
.manage-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  margin-right: 5px;
  transition: background-color 0.3s;
}

.send-btn:hover,
.manage-btn:hover {
  background-color: #40a9ff;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 5px;
}

.page-btn {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  border: 1px solid #d9d9d9;
  background: transparent;
  cursor: pointer;
  border-radius: 4px;
}

.page-btn.active {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.page-jump {
  margin: 0 5px;
}

.page-input {
  width: 50px;
  height: 32px;
  text-align: center;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.confirm-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  margin-left: 5px;
}

.message-dialog,
.manage-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 4px;
  width: 600px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.dialog-title {
  font-weight: bold;
}

.close-btn {
  background: transparent;
  border: none;
  font-size: 20px;
  cursor: pointer;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

textarea,
input {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: vertical;
}

.dialog-footer {
  padding: 10px 20px;
  text-align: right;
  border-top: 1px solid #f0f0f0;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
  padding: 6px 16px;
  border-radius: 4px;
  margin-right: 10px;
  cursor: pointer;
}

.confirm-send-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1001;
}
</style>
